package com.tom.jmgd.core.yun;

import com.alibaba.fastjson.JSONObject;
import com.tom.jmgd.common.HttpClientUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
public class gdyfYunsUnit {
    private  String token;
    private  Long timeStamp;
    @Value("${yuns.admin-user}")
    private  String adminUser;
    @Value("${yuns.admin-password}")
    private  String adminPwd;
    @Value("${yuns.huoban-cron-trigger}")
    private  String huobanCronTrigger;
    @Value("${yuns.h2-cron-trigger}")
    private  String h2CronTrigger;
    public  String createToken() throws IOException {
        Date d = new Date();
        if(StringUtils.isNotEmpty(token))  {
            /////一小时内
            if((d.getTime() - timeStamp)<=3555000) {
                return token;
            }
        }
        String tokenUrl = "http://yuns.jmgdyf.com/api/oauth/token?client_id=api&client_secret=c31b32364ce19ca8fcd150a417ecce58&username="+ adminUser +"&password="+adminPwd+"&grant_type=password&scope=read";
        Header[] headers = new Header[] { new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) };
        StringEntity stringEntity = new StringEntity("", ContentType.create("application/json", "UTF-8"));
        HttpResponse response = HttpClientUtils.post(tokenUrl, headers, stringEntity);
        HttpEntity entity = response.getEntity();
        String str = EntityUtils.toString(entity);
        JSONObject parse = JSONObject.parseObject(str);
        token = parse.get("access_token").toString();
        timeStamp = d.getTime();
        return token;
    }
    public  String getHuobanCronTrigger() {
        return huobanCronTrigger;
    }
    public  String getH2CronTrigger() {
        return h2CronTrigger;
    }
}
